#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")

const int CLIENT_PORT=25001; /*the client port number*/

#pragma pack(push,2)
typedef struct  
{
	int x[4];
	int y[4];
}MarkerCoord;
#pragma  pack(pop)

typedef union
{
	MarkerCoord coord;
	char bytes[32];
}MarkerPacket;

MarkerCoord cornerCoord;
MarkerPacket mPacket;

int main(int argc,char* argv[]){
	struct sockaddr_in serverAddr; /*server address*/
	struct sockaddr_in clientAddr; /*client address*/

	int clientSock; /*client sock*/
	char buf[100]; /*buffer the message send and receive*/
	int serverPort; /*protocl port*/
	int len=sizeof(struct sockaddr);

	WSADATA wsaData;
	WSAStartup(0x0202,&wsaData); /*windows socket startup */

	memset((char*)&clientAddr,0,sizeof(clientAddr));
	clientAddr.sin_family=AF_INET; /*set client address protocol family*/
	clientAddr.sin_addr.s_addr=INADDR_ANY;
	clientAddr.sin_port=htons((u_short)CLIENT_PORT); /*set client port*/

	serverAddr.sin_family=AF_INET;

	if (argc>2){
		serverAddr.sin_addr.s_addr=inet_addr(argv[1]);/*get the ip address*/
		if (serverAddr.sin_addr.s_addr==INADDR_NONE){
			fprintf(stderr,"bad ip address %s\n",argv[1]);
			exit(1);
		}

		serverPort=atoi(argv[2]);
		if (serverPort>0)
			serverAddr.sin_port=htons((u_short)serverPort);/*get the port*/
		else{
			fprintf(stderr,"bad port number %s\n",argv[2]);
			exit(1);
		}
	}else{
		fprintf(stderr,"input the ip address and port number");
		exit(1);
	}

	clientSock=socket(PF_INET,SOCK_DGRAM,0);/*create a socket*/
	if (clientSock<0){
		fprintf(stderr,"socket creating failed\n");
		exit(1);
	}

	if (bind(clientSock,(LPSOCKADDR)&clientAddr,len)<0){/*bind a client address and port*/
		fprintf(stderr,"bind failed\n");
		exit(1);
	}

	while(1)
	{
#if 0
		memset(buf,0,sizeof(buf));
		printf("\nClient--->: ");
		gets(buf);
		sendto(clientSock,buf,strlen(buf),0,(LPSOCKADDR)&serverAddr,len);
		if(strcmp(buf,"end")==0) break; /* send "end" to exit loop */

		memset(buf,0,sizeof(buf));
		recvfrom(clientSock,buf,sizeof(buf),0,(LPSOCKADDR)&serverAddr,&len);

		// moderator note: This code is a buffer overflow attack waiting to happen

		if(strcmp(buf,"end")==0) break; /* receive "end" to exit loop */
		if(strcmp(buf,"close")==0) return 1; /* receive "close" to close both */
		printf("\n--->From the server: ");
		printf("%s",buf);
#endif
		sendto(clientSock,buf,strlen(buf),0,(LPSOCKADDR)&serverAddr,len);

		recvfrom(clientSock,mPacket.bytes,sizeof(cornerCoord),0,(LPSOCKADDR)&serverAddr,&len);

		printf("(%d,%d),(%d,%d),(%d,%d),(%d,%d)\n",mPacket.coord.x[0],mPacket.coord.y[0],mPacket.coord.x[1],mPacket.coord.y[1],mPacket.coord.x[2],mPacket.coord.y[2],mPacket.coord.x[3],mPacket.coord.y[3]);

		Sleep(0);
	}

	closesocket(clientSock);
	WSACleanup();

	return 1;
}